package cn.always.xiajia.framework.mybatis.core.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import cn.always.xiajia.framework.common.util.ExtCollUtil;
import cn.always.xiajia.framework.common.util.ExtServletUtil;
import cn.always.xiajia.framework.common.util.ExtStringUtil;
import cn.always.xiajia.framework.security.core.entity.LoginUser;
import cn.always.xiajia.framework.security.core.util.SecurityFrameworkUtils;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public abstract class BaseController {

	@Resource
	protected HttpServletRequest request;

	@Resource
	protected HttpServletResponse response;

	/**
	 * 当前页
	 * 
	 * @return
	 */
	protected Integer getPageNo() {
		return ExtServletUtil.getParameterToInt("pageNo") == null ? 1 : ExtServletUtil.getParameterToInt("pageNo");
	}

	/**
	 * 每页条数，最大值为 1000
	 * 
	 * @return
	 */
	protected Integer getPageSize() {
		return ExtServletUtil.getParameterToInt("pageSize") == null ? 10 : ExtServletUtil.getParameterToInt("pageSize");
	}

	/**
	 * 排序字段
	 * 
	 * @return
	 */
	protected String getSort() {
		return ExtServletUtil.getParameter("sort");
	}

	/**
	 * 排序类型
	 * 
	 * @return
	 */
	protected String getDir() {
		return ExtServletUtil.getParameter("dir");
	}

	/**
	 * 排序类型返回
	 * 
	 * @return
	 */
	protected List<OrderItem> getOrderItems() {
		String sorts = getSort();
		String dirs = getDir();
		List<OrderItem> orderItems = new ArrayList<>();
		if (!ExtStringUtil.isBlank(sorts) && !ExtStringUtil.isBlank(dirs)) {
			String[] sortsArr = sorts.split(",");
			String[] dirsArr = dirs.split(",");
			for (int i = 0; i < sortsArr.length; i++) {
				String sort = sortsArr[i];
				String dir = dirsArr[i];
				OrderItem orderItem = new OrderItem();
				orderItem.setColumn(sort);
				if ("asc".equals(dir) || "ASC".equals(dir)) {
					orderItem.setAsc(true);
				} else {
					orderItem.setAsc(false);
				}
				orderItems.add(orderItem);
			}
		}
		return orderItems;
	}

	/**
	 * 分页不需要计算count
	 * 
	 * @param <T>
	 * @param cls
	 * @return
	 */
	protected <T> Page<T> buildPage(Class<T> cls) {
		Page<T> page = new Page<T>(this.getPageNo(), this.getPageSize(), false);
		List<OrderItem> orderItems = getOrderItems();
		if (!ExtCollUtil.isEmpty(orderItems)) {
			page.addOrder(orderItems);
		}
		return page;
	}

	/**
	 * 需要计算count
	 * 
	 * @param <T>
	 * @param cls
	 * @return
	 */
	protected <T> Page<T> buildPageCount(Class<T> cls) {
		Page<T> page = new Page<T>(this.getPageNo(), this.getPageSize(), true);
		List<OrderItem> orderItems = getOrderItems();
		if (!ExtCollUtil.isEmpty(orderItems)) {
			page.addOrder(orderItems);
		}
		return page;
	}

	protected Map<String, Object> buildParams() {
		Map<String, Object> params = ExtServletUtil.getParametersStartingWith(request);
		if (params == null || params.isEmpty()) {
			Map<String, Object> requestBody = this.getRequestBody();
			requestBody.forEach((k, v) -> {
				if (k.startsWith("filter_")) {
					params.put(k.replace("filter_", ""), v);
				}

			});
		}
		return params;
	}

	@SuppressWarnings("unchecked")
	protected Map<String, Object> getRequestBody() {
		try {
			HttpServletRequest httpServletRequest = ExtServletUtil.getRequest();
			Map<String, Object> requestBody = (Map<String, Object>) httpServletRequest.getAttribute("RequestBody");
			if (requestBody == null) {
				String b = ExtServletUtil.getBody(httpServletRequest);
				if (!ExtStringUtil.isBlank(b)) {
					requestBody = JSONUtil.parseObj(b);
					httpServletRequest.setAttribute("RequestBody", requestBody);
				}
			}
			return requestBody == null ? new HashMap<>() : requestBody;
		} catch (Exception e) {
			log.info("----getRequestBody--Exception-------" + e.getMessage(), e);
			return new HashMap<>();
		}
	}

	protected LoginUser getLoginUser() {
		return SecurityFrameworkUtils.getLoginUser();
	}

	protected Long getLoginUserId() {
		return SecurityFrameworkUtils.getLoginUserId();
	}

	protected String getLoginUserCode() {
		return SecurityFrameworkUtils.getLoginUserCode();
	}

	protected String getLoginUserName() {
		return SecurityFrameworkUtils.getLoginUserName();
	}

	protected String getLoginUserType() {
		return SecurityFrameworkUtils.getLoginUserType();
	}

}
